﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro;
using Csla;
using ProjTemp.Desktop.Common.Container;
using MahApps.Metro.Controls.Dialogs;
using ProjTemp.Desktop.Common.View;

namespace ProjTemp.Desktop.Common.Controls
{
    /// <summary>
    /// Interaction logic for CustomMetroWindow.xaml
    /// </summary>
    public class CustomMetroWindow : MetroWindow, IContainer
    {
        protected SimpleDialog _popupDialog = null;

        public CustomMetroWindow()
        {
            this.Initialize();
            this.Loaded += new RoutedEventHandler(CustomMetroWindow_Loaded);
        }

        protected virtual void Initialize()
        {
            this.LoadResourceDictionary();
            this.InitializeMisc();
        }

        private void LoadResourceDictionary()
        {
            //var resourceDictionary = new ResourceDictionary();
            //resourceDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedSingleRowTabControl.xaml") });
            //resourceDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/ProjTemp.Desktop.Common;component/Themes/BusyIndicator.xaml") });
            //resourceDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/MahApps.Metro.Resources;component/Icons.xaml") });
            //resourceDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml") });
            //resourceDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml") });
            
            //this.Resources = resourceDictionary;
        }

        private void InitializeMisc()
        {
            //Normal
            //this.MinHeight = StyleConst.WindowMinHeight;
            //this.MinWidth = StyleConst.WindowMinWidth;
            this.TitleCaps = false;
            this.SetResourceReference(GlowBrushProperty, StyleConst.AccentColorBrushKey);
        }

        void CustomMetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //Initialize the popup dialog
            this._popupDialog = new SimpleDialog();
            this._popupDialog.ShowTitle = false;
            this._popupDialog.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            var grid = new Grid();
            //Container groupbox
            var groupBox = new GroupBox() { Margin = new Thickness(0) };
            grid.Children.Add(groupBox);
            //Close button
            var path = new Path() { Fill = new SolidColorBrush(Colors.White), SnapsToDevicePixels = true };
            path.Data = Geometry.Parse(StyleConst.CloseImagePathData);
            var button = new Button() { Width = 24, Height = 24, VerticalAlignment = System.Windows.VerticalAlignment.Top, HorizontalAlignment = System.Windows.HorizontalAlignment.Right};
            button.SetResourceReference(FrameworkElement.StyleProperty, StyleConst.IronicallyNamedChromelessButtonStyleKey);
            button.Content = path;
            button.Click += new RoutedEventHandler((s, re) => { this.DoClose();});
            grid.Children.Add(button);
            groupBox.SetResourceReference(BackgroundProperty, StyleConst.AccentColorBrushKey);
            groupBox.SetResourceReference(BorderBrushProperty, StyleConst.AccentColorBrushKey);
            this._popupDialog.DialogBody = grid;
        }

        protected virtual void ChangeTheme(Accent accent, Theme theme)
        {
            ThemeManager.ChangeTheme(this, accent, theme);
        }

        #region IContainer

        protected event EventHandler PopupDialogClosed;
        protected object PopupDialogHeader { get; set; }
        protected object PopupDialogContent { get; set; }
        protected object PopupDialogReturnValue { get; set; }

        event EventHandler IContainer.Closed
        {
            add { this.PopupDialogClosed += value; }
            remove { this.PopupDialogClosed -= value; }
        }

        object IContainer.Owner
        {
            get
            {
                return this;
            }
            set
            {
                //do nothing
            }
        }

        object IContainer.Title
        {
            get
            {
                return PopupDialogHeader;
            }
            set
            {
                PopupDialogHeader = value;
            }
        }

        object IContainer.Content
        {
            get
            {
                return PopupDialogContent;
            }
            set
            {
                this.PopupDialogContent = value;
            }
        }

        void IContainer.Show(ContainerSetting setting)
        {
            if (this.Dispatcher.CheckAccess())
                this.DoShow();
            else
                Dispatcher.Invoke(new Action(() =>
                {
                    this.DoShow();
                }));
        }

        private void DoShow()
        {
            var containerGrid = this._popupDialog.DialogBody as Grid;
            if (containerGrid == null || containerGrid.Children.Count <= 0) return;

            var containerGroupBox = containerGrid.Children[0] as GroupBox;
            if (containerGroupBox != null)
            {                
                containerGroupBox.Header = this.PopupDialogHeader;
                containerGroupBox.Content = this.PopupDialogContent;
                if (this.PopupDialogContent != null && this.PopupDialogContent is VBase)
                {
                    Binding headerBinding = new Binding(DesktopConst.ViewHeaderPropertyName);
                    headerBinding.Source = PopupDialogContent;
                    headerBinding.Mode = BindingMode.TwoWay;
                    containerGroupBox.SetBinding(HeaderedContentControl.HeaderProperty, headerBinding);
                }
                containerGroupBox.SetResourceReference(ForegroundProperty, StyleConst.BlackColorBrushKey);
                this.ShowMetroDialogAsync(this.PopupDialogHeader == null ? string.Empty : this.PopupDialogHeader.ToString(), this._popupDialog);
            }
        }

        private void DoClose()
        {
            this.HideMetroDialogAsync(this._popupDialog);
            if (this.PopupDialogClosed != null)
            {
                this.PopupDialogClosed(this, new EventArgs());
                this.PopupDialogClosed = null;
            }
        }

        /// <summary>
        /// Won't implement this method
        /// </summary>
        /// <param name="setting"></param>
        void IContainer.ShowNonModal(ContainerSetting setting)
        {
            throw new NotImplementedException();
        }

        void IContainer.Close()
        {
            if (this.Dispatcher.CheckAccess())
                this.DoClose();
            else
                Dispatcher.Invoke(new Action(() =>
                {
                    this.DoClose();
                }));
        }

        object IContainer.ReturnValue
        {
            get
            {
                return this.PopupDialogReturnValue;
            }
            set
            {
                this.PopupDialogReturnValue = value;
            }
        }

        #endregion
        
    }
}